package quickAdd.client;

import com.google.gwt.user.client.ResponseTextHandler;
import com.google.gwt.http.client.URL;

import java.util.List;
import java.util.ArrayList;

/**
 * Encapsulates a GData login
 */
public class Auth
{
    static interface AuthorizationComplete {
        void authorizationBeginning();
        void authorizationComplete();
        void authorizationFailed();
    }

    private String passwd, email;
    private String token;
    private List /*<AuthorizationComplete>*/ listeners = new ArrayList();

    public Auth( AuthorizationComplete listener )
    {
        addListener( listener );
    }

    public void addListener( AuthorizationComplete listener ) {
        listeners.add(listener);
    }

    /**
     * you must set email and pass first
     */
    public void authenticate()
    {
        QuickAdd.out( "getAuth..." );
        if ( passwd == null || email == null )
            notifyFailed();

        notifyBeginning();
        
        String postData = "accountType=GOOGLE&Email="+email+"&Passwd="+passwd+"&source=quickadd-testapp-1&service=wise";
        QuickAdd.out( "postData="+postData );
        String url ="https://www.google.com/accounts/ClientLogin";
        ResponseTextHandler handler = new ResponseTextHandler() {
            public void onCompletion( String responseText ) {
                QuickAdd.out("authentication complete.");
                try {
                    token =parseAuth(responseText);
                    notifyComplete();
                } catch ( Exception e ) {
                    notifyFailed();
                }
            }
        };

        HttpUtil.doFormPost( url, postData, handler);
    }

    /**
     * After authentication
     */
    public String getToken()
    {
        if ( token == null )
            throw new RuntimeException("need to authorize first");
        return token;
    }

    static String parseAuth( String s ) {
        int i = s.indexOf("Auth");
        return s.substring(i+5, s.length()-1); // Auth=
    }


    /**
     * plain text, will be encoded
     */
    public void setPasswd( String passwd )
    {
        this.passwd = URL.encodeComponent(passwd);
    }

    /**
     * plain text, will be encoded
     */
    public void setEmail( String email )
    {
        if ( email.indexOf("@") ==-1)
            email+="@gmail.com";
        this.email = URL.encodeComponent(email);
    }

    private void notifyComplete() {
        for ( int i = 0; i < listeners.size(); i++ )
            ((AuthorizationComplete)listeners.get( i )).authorizationComplete();
    }
    private void notifyFailed() {
        for ( int i = 0; i < listeners.size(); i++ )
            ((AuthorizationComplete)listeners.get( i )).authorizationFailed();
    }
    private void notifyBeginning() {
        for ( int i = 0; i < listeners.size(); i++ )
            ((AuthorizationComplete)listeners.get( i )).authorizationBeginning();
    }

}
